<?php
declare (strict_types=1);

namespace app\shop_admin\service;

use app\shop_admin\model\Store as admin;
use app\utils\TrimData;

class StoreService
{

    private $user;
    private $merchantId;

    public function __construct()
    {
        global $user;
        $this->user = $user;
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $list = admin::where(['status' => 1])
            ->field('id,name')
            ->select();
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function findAll(array $data, int $page = 1, int $size = 10)
    {
        $admin = admin::field(
            [
                'id',
                'merchant_id',
                'name',
                'mobile',
                'district',
                'address',
                'longitude',
                'latitude',
                'remark',
                'audit',
                'status',
                'create_time',
                'update_time'
            ]);
//        if ($this->merchantId == 1)
        $admin->with(['merchant']);
        $admin = TrimData::searchDataTrim($admin, $data, ['name', 'mobile', 'begin_date', 'end_date']);

        $list = $admin->where($data)->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 保存数据
     * @param array $data
     * @return array
     */
    public function save(array $data)
    {
//        if ($this->merchantId == 1) {
            $data['audit'] = 1;
//        }
        $model = admin::create($data);
        return [HTTP_CREATED, $model];
    }

    /**
     * 读取一条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = admin::find($id);
        return [HTTP_SUCCESS, $model];
    }


    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return array
     */
    public function update(int $id, array $data)
    {
        $update_time = $data['update_time'];
        unset($data['update_time']);


        $admin = admin::where('update_time', $update_time)
            ->where('id', $id)
            ->save($data);

        return [HTTP_CREATED, $admin];
    }

    /**
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        admin::destroy($id);
        return HTTP_NOCONTEND;
    }

}
